<template>



  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="100%" @ok="handleSubmit">
    <div ref="topElRef">
      <div>
        试卷名称 {{dataList?.paperName}}
      </div>
      <div style="display: flex" v-if="dataList.userPaperId">
        <div>考生:{{dataList.userName}}</div> ---<div style="margin-left: 5px;">考试时间：{{dataList.createTime}}</div>
      </div>

      <div v-if="paperInfo.paperId&&dataList.userPaperId">
        <!--    团队卷的答题结果-->
        <div v-if="paperInfo.ruleType==1">
          <div  style="display: flex">
            <div style="width: 150px">已回答:</div>
            <div>{{userScore.anserNum}}</div>题

          </div>
          <div v-if="anser_list.length==0&&anserLog.id">
            原始答题记录 {{anserLog.id}} 提交时间{{anserLog.createTime}}
            <div style="margin-top: 3px;margin-bottom: 3px">
              <vxe-button content="重新计算分数" status="primary" :loading="loading" @click="againCountByAnserLogFn" size="mini"></vxe-button>
            </div>
          </div>
          <div  style="display: flex">
            <div style="width: 150px"> 答对:</div>
            <div>{{userScore.trueNum?userScore.trueNum:0}}</div>题</div>
          <div style="display: flex">
            <div style="width: 150px">答错和未答:</div>
            <div style="color: #c65206">{{userScore.erroNum?userScore.erroNum:0}}</div>题</div>
        </div>
        <!--      面试卷的答题结果-->
        <div v-if="paperInfo.ruleType==0">
          汇总:
          <div v-for="(item,index) in mianShiResult">
            <div class="ansers-row" style="border-top: 1px solid #e0e0e0;"></div>

            <div style="display: flex;justify-content: space-between;">
              <div class="ansers-row">{{item.groupName}}</div>
              <Button type="primary" size="small" @click="againGroupFn(item)">重考</Button>
            </div>
            <div v-if="item.questionType=='性格测试题'">
              <div class="ansers-row"  style="display: flex;">
                <div style="margin-right: 5px;"> <span style="color: gray">C:力量型</span>({{item.result2.c?item.result2.c:0}})</div>
                <div style="margin-right: 5px;"> <span style="color: gray">S:活泼型</span>({{item.result2.s?item.result2.s:0}})</div>
                <div style="margin-right: 5px;"> <span style="color: gray">P:和平型</span>({{item.result2.p?item.result2.p:0}})</div>
                <div style="margin-right: 5px;"> <span style="color: gray">M:完美型</span>({{item.result2.m?item.result2.m:0}})</div>
              </div>
              <div v-html="xingge_zhushi" v-if="xingge_zhushi"></div>
            </div>


            <div >
              <div v-if="item.questionType=='选择题'" >
                <div v-if="xc_result_list.length>0" class="ansers-row">
                  <div class="ansers-row" v-for="(item,index) in xc_result_list" :key="index">
                    <span>{{item.name}}</span>
                    <span style="color: green;margin-left: 5px;">正确</span>: <span style="padding-left: 2px;padding-right: 2px;">{{item.t}}</span>题
                    <span style="color: red;margin-left: 5px;">错误</span>:<span style="padding-left: 2px;padding-right: 2px;">{{item.f}}</span>题

                  </div>
                </div>

                <div v-else>
                  <!-- <view class="ansers-row">
                  最终得分:{{item.result1.resultScore}}分
                </view> -->
                  <div v-if="item.result1.trueNum" class="ansers-row">
                    <span style="color: green;">正确题数</span>: <span style="padding-left: 2px;padding-right: 2px;">{{item.result1.trueNum}}</span>题
                  </div>
                  <div v-if="item.result1.erroNum" class="ansers-row">
                    <span style="color: red;">错误题数</span>:<span style="padding-left: 2px;padding-right: 2px;">{{item.result1.erroNum}}</span>题
                  </div>
                </div>

              </div>
            </div>

          </div>

        </div>
      </div>
    </div>

    <vxe-grid ref="tableRef" v-bind="gridOptions" :style="{height: (contentHeight*0.9)+'px'}">
      <template #toolbar_buttons>
<!--           <Button type="primary" size="small" @click="printEvent ">点击打印</Button>-->
      </template>
      <template #action="{ row }">
        <TableAction outside :actions="getActions(row)" />
      </template>
<!--      <template #expand_content="{ row }">-->
<!--        <div v-for="item in row.options" :key="item.userOptionId" style="height: 20px">-->
<!--          <div style="margin-top: 5px">{{item.letter}}：：{{ item.title }}</div>-->
<!--        </div>-->
<!--      </template>-->

    </vxe-grid>

    <Modal v-model:visible="visible" :title="title" @ok="subFn" ></Modal>

    <Modal v-model:visible="visible2" :title="title2" @ok="subAllFn" ></Modal>
    <template #footer>
      <vxe-button type="primary" size="small" status="error" @click="userPaperBrakeAllFn" content="重考该考生整张试卷"></vxe-button>
      <vxe-button size="small"  content="关闭" @click="closeDrawer"></vxe-button>

    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup>



import { BasicTable, useTable, TableAction } from '@/components/Table';
import { ref, computed, unref, h, toRaw, reactive } from 'vue';
import {Button, Modal} from 'ant-design-vue';
import {
  getUserScore,
  getPaperByPublishPaperId,
  manageUserScoreByMainShi,
  userPaperBrakeGroup,
  userPaperBrakeAll,
  againCountByAnserLog,
  getCountByAnserLog
} from '@/api/heng/ex';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { useDrawer } from '@/components/Drawer';

import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';

import {
  titleGroupform,
  titleGroupColumns,
  userAnsersColumns
} from './role.data';
import { VxeUI, VxeTableInstance } from 'vxe-table'

import { BasicModal, useModalInner } from '@/components/Modal';
import { Form, FormItem, Input, InputNumber, DatePicker, Select, Switch } from 'ant-design-vue';
import SelectQuestionDrawer from '@/views/components/ex/SelectQuestionDrawer/SelectQuestionDrawer.vue';

import { getUserAnsers, categoryList } from '@/api/heng/ex';


import { useMessage } from "@/hooks/web/useMessage";
import util from '@/utils/util';

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const { createMessage } = useMessage();

const chooseQuestion = useDrawer();

const id = ref("")

const contentHeight = ref(window.innerHeight);

const loading=ref(false);

const userScore=ref({});
const tableRef = ref();
const topElRef=ref();

const visible=ref(false);
const title=ref("");
const subData=ref({});

const visible2=ref(false);
const title2=ref("");
const subData2=ref({});

const dataList = ref({});
const countNum = ref(0);
const paperInfo = ref({});//试卷信息
const anserLog=ref({});//原始考试记录

const anserLogJson=ref({});
const anser_list=ref([]);//答题列表

const mianShiResult=ref([]);//面试卷的考试结果
const xingge_zhushi=ref({});//性格与沟通注释
const xc_result_list=ref([]);//行测的统计结果

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: userAnsersColumns,
  keepSource:true,
  filterConfig: {
    // remote: true,
  },
  treeConfig: {
    rowField: 'type',
    childrenField: 'options',
    expandAll: false
  },
  expandConfig: {},
  exportConfig:{},
  showFooter: true,
  footerData: [
    { title: '合计' }
  ],
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    enabled: false,
  },
});




const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //打开弹层后的回调
  // resetFields();
  setDrawerProps({ confirmLoading: false });
  // console.log("---data:",data)
  dataList.value = data;
  id.value = data.publishPaperId;
  initFn();
});

const getTitle = computed(() => ('试卷答题情况'));


function initFn(){
  getUserAnsersFn();
  // getUserScoreFn();
  getPaperByPublishPaperIdFn();
}
//async function handleSubmit()

async function handleSubmit() {
  try {
    // console.log("--dataList.value:",dataList.value)
    // emit('success', values);
    closeDrawer();

  } catch (e) {
    console.log(e)
  } finally {
    setDrawerProps({ confirmLoading: false });

  }
}

function getUserAnsersFn(){
  let json={publishPaperId:id.value};
  if(dataList.value.userName){
    json.userName=dataList.value.userName
  }
  getUserAnsers(json).then(res => {
    if(res.code==200){
      let arr=res.data;
      if(arr.length>0){
        let all=[];

        let xc_result=[];
        let y_map={name:"语言测试",t:0,f:0};//语言测试
        let s_map={name:"数资测试",t:0,f:0};
        let p_map={name:"判断题",t:0,f:0};
        let iz_xince=false;
        for(let i=0;i<arr.length;i++){
          let item=arr[i];
          let type=item.type;
          let publishGroupName=item.publishGroupName;
          let sort=item.sort;
          if(type=="性格与沟通"){

            if(sort==1){
              all.push({groupName:"性格测试"})
            }
          }else if(publishGroupName=="行测"){

            iz_xince=true;
            /**
             * 划分模块名称
             */
            if(sort==1){
              all.push({groupName:"语言测试"})
            }
            if( sort==10){
              all.push({groupName:"数资测试"})
            }
            if(sort==20){
              all.push({groupName:"判断题"})
            }
            /**
             * 统计分数
             */
            if(sort>0&&sort<11){
              if(item.isTrue==1){
                y_map.t+=1
              }else{
                y_map.f+=1

              }
            }
            if(sort>10&&sort<21){
              if(item.isTrue==1){
                s_map.t+=1
              }else{
                s_map.f+=1

              }
            }
            if(sort>20&&sort<31){
              if(item.isTrue==1){
                p_map.t+=1
              }else{
                p_map.f+=1

              }
            }
          }

          all.push(arr[i]);
        }
        if(iz_xince){
          xc_result.push(y_map);
          xc_result.push(s_map);
          xc_result.push(p_map);
          xc_result_list.value=xc_result;
        }

        // console.log("--xc_result:",xc_result)
        tableRef.value.reloadData(all);
        gridOptions.footerData[0].title = "共" +all.length + "条";
      }else{
        tableRef.value.reloadData(arr);
        gridOptions.footerData[0].title = "共" +arr.length + "条";
      }
      anser_list.value=arr;
      anserLogJson.value=json;
      getCountByAnserLogFn();
    }else{
      createMessage.error(res.message);
    }
  })
}

function getActions(record) {
  let arr = [
    {
      // icon: 'ant-design:delete-outlined',
      // label: '删除',
      // color: 'error',
      // onClick: handleClose.bind(null, record)

    }
  ];


  return arr;
}

const count = ref(0);
const addNum = ref(0);

function handleClose(record: Recordable) {

  tableRef.value.remove(record);
  addNum.value = addNum.value - 1;
  countTableNum()
}


function countTableNum() {
  // let t_list = tableRef.value.getTableData();
  // console.log("----countTableNum:", t_list);

}


async function countByCategoryIdFn() {


}

/**
 * 获取试卷信息
 */
function getPaperByPublishPaperIdFn(){
  getPaperByPublishPaperId({publishPaperId:id.value}).then(res => {
    if(res.code==200){
      paperInfo.value = res.data;
      if(paperInfo.value.ruleType==1){
        getUserScoreFn();
      }else{
        manageUserScoreByMainShiFn();
      }
    }else{
      createMessage.error(res.message);
    }
  });
}

/**
 * 获取面试题考试结果
 */
function manageUserScoreByMainShiFn(){
  manageUserScoreByMainShi({userPaperId:dataList.value.userPaperId}).then(res => {
    if(res.code==200){
      mianShiResult.value = res.data;

      //性格与沟通注释显示
      let xingge_zhushi_map=new Map();
      xingge_zhushi_map.set("C","力量型</br>\n" +
        "优点：善于管理、主动积极</br>\n" +
        "弱点：缺乏耐心、感觉迟钝</br>\n" +
        "反感：优柔寡断</br>\n" +
        "追求：工作效率、支配地位</br>\n" +
        "担心：被驱动、强迫</br>\n" +
        "动机：获胜、成功</br>\n" +
        "（天生的领袖；对改变的迫切需要；目标导向、工作分派）");
      xingge_zhushi_map.set("M","完美型</br>\n" +
        "优点：做事讲求条理、善于分析</br>\n" +
        "弱点：完美主义、过于苛刻</br>\n" +
        "反感：盲目行事</br>\n" +
        "追求：精细准确、一丝不苟</br>\n" +
        "担心：批评于非议</br>\n" +
        "动机：进步</br>\n" +
        "（信条：质量比数量重要；工程人员：施工、监理；深深的关怀和同情心）");
      xingge_zhushi_map.set("P","和平型</br>\n" +
        "优点：恪尽职守、善于倾听</br>\n" +
        "弱点：过于敏感、缺乏主见</br>\n" +
        "反感：感觉迟钝</br>\n" +
        "追求：被人接受、生活稳定</br>\n" +
        "担心：突然的变革</br>\n" +
        "动机：团结、归属感</br>\n" +
        "（中庸之道，最接近中国传统文化“和为贵”；低调、随和、镇定、耐心、乐天知命；具备行政能力）");
      xingge_zhushi_map.set("S","活泼型</br>\n" +
        "优点：善于劝导，着重别人关系</br>\n" +
        "弱点：缺乏条理，粗心大意</br>\n" +
        "反感：循规蹈矩</br>\n" +
        "追求：广受欢迎与喝彩</br>\n" +
        "担心：失去声望</br>\n" +
        "动机：别人的认同</br>\n" +
        "（高速公路边的花；永远年轻的心；计划的首尾）");

      for (let i = 0; i < mianShiResult.value.length; i++) {
        let item=mianShiResult.value[i];
        //获取性格测试题 评分最大的那一项
        if(item.questionType=='性格测试题'){
          let max_score=0;let max_option="";
          if(max_score<item.result2.c){
            max_score=item.result2.c;
            max_option="C";
          }
          if(max_score<item.result2.s){
            max_score=item.result2.s;
            max_option="S";
          }
          if(max_score<item.result2.p){
            max_score=item.result2.p;
            max_option="P";
          }
          if(max_score<item.result2.m){
            max_score=item.result2.m;
            max_option="M";
          }

          xingge_zhushi.value=xingge_zhushi_map.get(max_option);
        }
      }


    }else{
      createMessage.error(res.message);
    }
  })
}

/**
 * 获取原始考试记录
 */
function getCountByAnserLogFn(){
  getCountByAnserLog(anserLogJson.value).then((res) => {
    if(res.code==200){
      anserLog.value = res.data;
    }else {
      createMessage.error(res.message);
    }
  })
}

/**
 * 分数为0时重新进行计算
 */
function againCountByAnserLogFn(){
  loading.value = true;
  againCountByAnserLog(anserLog.value).then((res) => {
    if(res.code==200){
      initFn();
      createMessage.success(res.message);
    }else {
      createMessage.error(res.message);
    }
  }).finally(()=>{
    loading.value = false;
  })
}


async function addFn() {
  const values = await validate();
  //console.log("--addFn-values:", values);
  // tableRef.value.insertAt({ questionId: id.value, isTrue: 0 }, -1);
  let t_list = tableRef.value.getTableData().tableData;
  t_list.forEach(item => {
    item.isChecked = true;
  })
  values.select_list=t_list;
  chooseQuestion[1].openDrawer(true, values)
}


function handleSuccess(list) {
  list.forEach((item) => {
    item.createTime=null;
  })
  addNum.value = addNum.value + list.length;
  // console.log("----c:", list);
  tableRef.value.insert(list);
  countTableNum();
}


function handleFieldValueChange(e) {
  console.log("---handleFieldValueChange:", e);
  if (e == 'type') {
    countByCategoryIdFn();
  }
}

function handleTreeChange(e1, e2, model, field) {
  // console.log("---handleTreeChange:", e1, e2);
  let categoryName = e2[0];
  model.categoryName = categoryName;
}


function getUserScoreFn(){
  getUserScore({userPaperId:dataList.value.userPaperId}).then(res=>{
    if(res.code==200){
      userScore.value=res.data;
    }else{
      createMessage.error(res.message);
    }
  })
}

/**
 * 按照模块重考
 */
function againGroupFn(item){
  // console.log("---publishGroupId:", item.publishGroupId);
  // console.log("---userPaperId:",dataList.value.userPaperId)
  let json={
    publishGroupId:item.publishGroupId,
    userPaperId:dataList.value.userPaperId
  };
  visible.value=true;
  subData.value=json;
  title.value=`确定将该模块[${item.groupName}]进行重考?操作完成后 请前往告知考生 重进考试!`;
}

function subFn(){
  userPaperBrakeGroup(subData.value).then(res=>{
    if(res.code==200){
      visible.value=false;
      createMessage.success(res.message);
      initFn();
    }else{
      createMessage.error(res.message);
    }
  })
}

/**
 * 整张试卷重考
 */
function userPaperBrakeAllFn(){

  let json={
    userPaperId:dataList.value.userPaperId
  };
  visible2.value=true;
  subData2.value=json;
  title2.value=`确定将该 张试卷 [整张] 进行重考?操作完成后 请前往告知考生 重进考试!`;

}

function subAllFn(){
  userPaperBrakeAll(subData2.value).then(res=>{
    if(res.code==200){
      visible2.value=false;
      createMessage.success(res.message);
      handleSubmit();
      // initFn();
    }else{
      createMessage.error(res.message);
    }
  })
}

const printEvent = async () => {
  const $table = tableRef.value
  if ($table) {
    const printRest = await $table.getPrintHtml()
    const topEl = topElRef.value
    const topHtml = topEl ? topEl.innerHTML : ''
    VxeUI.print({
      title: '考试结果单据',
      pageBreaks: [
        // 第一页
        {
          bodyHtml: topHtml + printRest.html
        }
      ]
    })
  }
}

</script>
<style lang="less">
.item-row {
  margin: 0 auto;

  //padding-left: 5%;
  .ant-form-item-label {
    flex: 0 0 28.5%;
    max-width: 28.5%;
  }
}

.lqfp-8 {
  //padding-left: 9% !important;

}
.ansers-row{
  margin-bottom: 8px;
}
</style>
